﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Diagnostics;
using System.Web.UI.WebControls;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Collections.ObjectModel;
using System.Collections;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Administration;
using PowerShellConsole.Jobs;

namespace PowerShellConsole.PageCode
{
    public class ScheduleScript : LayoutsPageBase
    {
        protected Literal litScriptName;
        protected InputFormControl ifcBeginDay;
        protected InputFormControl ifcEndDay;
        protected InputFormControl ifcBeginMonth;
        protected InputFormControl ifcEndMonth;
        protected InputFormControl ifcBeginDayOfWeek;
        protected InputFormControl ifcEndDayOfWeek;
        protected InputFormControl ifcBeginHour;
        protected InputFormControl ifcEndHour;
        protected InputFormControl ifcBeginMinute;
        protected InputFormControl ifcEndMinute;
        protected InputFormControl ifcBeginSecond;
        protected InputFormControl ifcEndSecond;
        protected InputFormControl ifcInterval;
        protected DropDownList ddlScheduleType;
        protected DropDownList ddlBeginDay;
        protected DropDownList ddlEndDay;
        protected DropDownList ddlBeginMonth;
        protected DropDownList ddlEndMonth;
        protected DropDownList ddlBeginDayOfWeek;
        protected DropDownList ddlEndDayOfWeek;
        protected DropDownList ddlBeginHour;
        protected DropDownList ddlEndHour;
        protected DropDownList ddlBeginMinute;
        protected DropDownList ddlEndMinute;
        protected DropDownList ddlBeginSecond;
        protected DropDownList ddlEndSecond;
        protected DropDownList ddlInterval;
        protected CheckBoxList chklJobs;

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            SPList scriptsList = SPContext.Current.Site.RootWeb.Lists["PowershellScripts"];
            litScriptName.Text = scriptsList.GetItemById(Convert.ToInt32(Request.QueryString["ID"])).Name;

            if (!Page.IsPostBack)
            {
                ddlScheduleType.Items.AddRange(new ListItem[] {
                    new ListItem(),
                    new ListItem("Minute schedule", "minute"),
                    new ListItem("Hourly schedule", "hourly"),
                    new ListItem("Daily schedule", "daily"),
                    new ListItem("Weekly schedule", "weekly"),
                    new ListItem("Monthly schedule", "monthly"),
                    new ListItem("Yearly schedule", "yearly")
                });
                for (int i = 0; i < 31; i++)
                {
                    ddlBeginDay.Items.Add(i.ToString());
                    ddlEndDay.Items.Add(i.ToString());
                }
                for (int i = 0; i < 12; i++)
                {
                    ddlBeginMonth.Items.Add(i.ToString());
                    ddlEndDay.Items.Add(i.ToString());
                }
                for (int i = 0; i < 7; i++)
                {
                    ddlBeginDayOfWeek.Items.Add(i.ToString());
                    ddlEndDayOfWeek.Items.Add(i.ToString());
                }
                for (int i = 0; i < 24; i++)
                {
                    ddlBeginHour.Items.Add(i.ToString());
                    ddlEndHour.Items.Add(i.ToString());
                }
                for (int i = 0; i < 60; i++)
                {
                    ddlBeginMinute.Items.Add(i.ToString());
                    ddlEndMinute.Items.Add(i.ToString());
                    ddlBeginSecond.Items.Add(i.ToString());
                    ddlEndSecond.Items.Add(i.ToString());
                    ddlInterval.Items.Add(i.ToString());
                }
                foreach (SPJobDefinition job in Site.WebApplication.JobDefinitions)
                {
                    if (job is ScriptRunnerJob)
                    {
                        chklJobs.Items.Add(new ListItem(job.Title + "(" + job.Schedule.ToString() + ")", job.Id.ToString()));
                    }
                }
            }

        }

        protected void buttonOk_OnClick(object sender, EventArgs e)
        {
            SPList scriptsList = SPContext.Current.Site.RootWeb.Lists["PowershellScripts"];
            string scriptFileName = scriptsList.GetItemById(Convert.ToInt32(Request.QueryString["ID"])).Name;

            SPSchedule schedule = null;
            switch (ddlScheduleType.SelectedValue)
            {
                case "minute":
                    schedule = new SPMinuteSchedule()
                    {
                        BeginSecond = Convert.ToInt32(ddlBeginSecond.SelectedValue),
                        EndSecond = Convert.ToInt32(ddlEndSecond.SelectedValue),
                        Interval = Convert.ToInt32(ddlInterval.SelectedValue)
                    };
                    break;
                case "hourly":
                    schedule = new SPHourlySchedule()
                    {
                        BeginMinute = Convert.ToInt32(ddlBeginMinute.SelectedValue),
                        EndMinute = Convert.ToInt32(ddlEndMinute.SelectedValue)
                    };
                    break;
                case "daily":
                    schedule = new SPDailySchedule()
                    {
                        BeginHour = Convert.ToInt32(ddlBeginHour.SelectedValue),
                        BeginMinute = Convert.ToInt32(ddlBeginMinute.SelectedValue),
                        BeginSecond = Convert.ToInt32(ddlBeginSecond.SelectedValue),
                        EndHour = Convert.ToInt32(ddlEndHour.SelectedValue),
                        EndMinute = Convert.ToInt32(ddlEndMinute.SelectedValue),
                        EndSecond = Convert.ToInt32(ddlEndSecond.SelectedValue)
                    };
                    break;
                case "weekly":
                    schedule = new SPWeeklySchedule()
                    {
                        BeginDayOfWeek = (DayOfWeek)Convert.ToInt32(ddlBeginDayOfWeek.SelectedValue),
                        BeginHour = Convert.ToInt32(ddlBeginHour.SelectedValue),
                        BeginMinute = Convert.ToInt32(ddlBeginMinute.SelectedValue),
                        BeginSecond = Convert.ToInt32(ddlBeginSecond.SelectedValue),
                        EndDayOfWeek = DayOfWeek.Sunday,
                        EndHour = Convert.ToInt32(ddlEndHour.SelectedValue),
                        EndMinute = Convert.ToInt32(ddlEndMinute.SelectedValue),
                        EndSecond = Convert.ToInt32(ddlEndSecond.SelectedValue)
                    };
                    break;
                case "monthly":
                    schedule = new SPMonthlySchedule()
                    {
                        BeginDay = Convert.ToInt32(ddlBeginDay.SelectedValue),
                        BeginHour = Convert.ToInt32(ddlBeginHour.SelectedValue),
                        BeginMinute = Convert.ToInt32(ddlBeginMinute.SelectedValue),
                        BeginSecond = Convert.ToInt32(ddlBeginSecond.SelectedValue),
                        EndDay = Convert.ToInt32(ddlEndDay.SelectedValue),
                        EndHour = Convert.ToInt32(ddlEndHour.SelectedValue),
                        EndMinute = Convert.ToInt32(ddlEndMinute.SelectedValue),
                        EndSecond = Convert.ToInt32(ddlEndSecond.SelectedValue)
                    };
                    break;
                case "yearly":
                    schedule = new SPYearlySchedule()
                    {
                        BeginMonth = Convert.ToInt32(ddlBeginMonth.SelectedValue),
                        BeginDay = Convert.ToInt32(ddlBeginDay.SelectedValue),
                        BeginHour = Convert.ToInt32(ddlBeginHour.SelectedValue),
                        BeginMinute = Convert.ToInt32(ddlBeginMinute.SelectedValue),
                        BeginSecond = Convert.ToInt32(ddlBeginSecond.SelectedValue),
                        EndMonth = Convert.ToInt32(ddlEndMonth.SelectedValue),
                        EndDay = Convert.ToInt32(ddlEndDay.SelectedValue),
                        EndHour = Convert.ToInt32(ddlEndHour.SelectedValue),
                        EndMinute = Convert.ToInt32(ddlEndMinute.SelectedValue),
                        EndSecond = Convert.ToInt32(ddlEndSecond.SelectedValue)
                    };
                    break;
            }

            ScriptRunnerJob job = new ScriptRunnerJob("Powershell Script Runner " + DateTime.Now.Ticks, Site.WebApplication);
            job.Schedule = schedule;
            job.Properties["script"] = scriptFileName;
            job.Update();

            Response.Redirect(Request.RawUrl);
        }

        protected void ddlSchedultTypeChange(object sender, EventArgs e)
        {
            switch (ddlScheduleType.SelectedValue)
            {
                case "minute":
                    showHide(false, false, false, false, false, true, true);
                    break;
                case "hourly":
                    showHide(false, false, false, false, true, false, false);
                    break;
                case "daily":
                    showHide(false, false, false, true, true, true, false);
                    break;
                case "weekly":
                    showHide(false, false, true, true, true, true, false);
                    break;
                case "monthly":
                    showHide(true, false, false, true, true, true, false);
                    break;
                case "yearly":
                    showHide(true, true, false, true, true, true, false);
                    break;
            }
        }

        private void showHide(bool day, bool month, bool dayOfWeek, bool hour, bool minute, bool second, bool interval)
        {
            ifcBeginDay.Visible = day;
            ifcEndDay.Visible = day;
            ifcBeginMonth.Visible = month;
            ifcEndMonth.Visible = month;
            ifcBeginDayOfWeek.Visible = dayOfWeek;
            ifcEndDayOfWeek.Visible = dayOfWeek;
            ifcBeginHour.Visible = hour;
            ifcEndHour.Visible = hour;
            ifcBeginMinute.Visible = minute;
            ifcEndMinute.Visible = minute;
            ifcBeginSecond.Visible = second;
            ifcEndSecond.Visible = second;
            ifcInterval.Visible = interval;
        }

        protected void btnRemove_OnClick(object sender, EventArgs e)
        {
            foreach (ListItem li in chklJobs.Items)
            {
                Site.WebApplication.JobDefinitions.Remove(new Guid(li.Value));
            }
            Response.Redirect(Request.RawUrl);
        }
    }
}
